//
//  WSManager+Rooms.m
//  mUBB
//
//  Created by Cosmin Stirbu on 1/18/13.
//  Copyright (c) 2013 Cosmin Stirbu. All rights reserved.
//

#import "WSManager+Rooms.h"
#import "RoomsHandler.h"
#import "RoomDetailsHandler.h"

@implementation WSManager (Rooms)

- (Ticket *)getRoomsByKeyword:(NSString *)keyWord take:(NSInteger)take skip:(NSInteger)skip delegate:(id<RoomsProtocol>)delegate {
    // Ticket
    Ticket *ticket = [[Ticket alloc] initWithId:ticketId++];
    // URL
    NSMutableString *url = [NSMutableString stringWithString:[UserDefaultsManager getObjectForKey:WS_ROOMS_SERVICE_KEY]];
    
    // Encode the keyword
    NSMutableString *unencodedString = [NSMutableString stringWithString:keyWord];
    [unencodedString replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [unencodedString length])];
    NSString *encodedString = (__bridge NSString *)CFURLCreateStringByAddingPercentEscapes(NULL,(CFStringRef)unencodedString, NULL,(CFStringRef)@"!*'();:@&=+$,/?%#[]",kCFStringEncodingUTF8 );
    
    // Append parameters
    [url appendFormat:@"?keyword=%@&take=%d&skip=%d", encodedString, take, skip];
    
    // Connection delegate
    connectionDelegate = [[RoomsHandler alloc] initWithDelegate:delegate ticket:ticket];
    
    // Make the request
    [self getRequestWithUrl:url andHeaders:nil];
    
    // Set Connection Delegate to nil
    connectionDelegate = nil;
    
    return ticket;
    
}

- (Ticket *)getDetailsForRoom:(Room *)room delegate:(id<RoomsProtocol>)delegate {
    // Ticket
    Ticket *ticket = [[Ticket alloc] initWithId:ticketId++];
    
    // Connection delegate
    connectionDelegate = [[RoomDetailsHandler alloc] initWithDelegate:delegate room:room ticket:ticket];
    NSString *url = room.selfUrl;
    if ([NSString isNullOrEmpty:url]) {
        url = [(NSString *)[UserDefaultsManager getObjectForKey:WS_ROOMS_SERVICE_KEY]stringByAppendingFormat:@"/%d", room.roomId];
    }
    // Make the request
    [self getRequestWithUrl:url andHeaders:nil];
    
    // Set Connection Delegate to nil
    connectionDelegate = nil;
    
    return ticket;
}

- (Ticket *)getRoomsForFaculty:(Faculty *)faculty delegate:(id<RoomsProtocol>)delegate {
    // Ticket
    Ticket *ticket = [[Ticket alloc] initWithId:ticketId++];
    NSString *url = [NSString stringWithFormat:@"%@/faculty/%d", [UserDefaultsManager getObjectForKey:WS_ROOMS_SERVICE_KEY], faculty.facultyId];
    
    // Connection delegate
    connectionDelegate = [[RoomsHandler alloc] initWithDelegate:delegate ticket:ticket];
    
    // Make the request
    [self getRequestWithUrl:url andHeaders:nil];
    
    // Set Connection Delegate to nil
    connectionDelegate = nil;
    
    return ticket;
}

@end
